package com.tudouji.project.produce.service.impl;

import com.flow.service.pojo.ResultParam;
import com.flow.service.pojo.result.FlowResult;
import com.github.pagehelper.PageHelper;
import com.tudouji.common.exception.CustomException;
import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.common.utils.sql.SqlUtil;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.framework.web.page.PageDomain;
import com.tudouji.framework.web.page.TableSupport;
import com.tudouji.project.bill.domain.Whinfo;
import com.tudouji.project.bill.domain.Whoutform;
import com.tudouji.project.bill.domain.Whoutformitem;
import com.tudouji.project.bill.service.impl.WhinfoServiceImpl;
import com.tudouji.project.bill.service.impl.WhoutformServiceImpl;
import com.tudouji.project.bill.service.impl.WhoutformitemServiceImpl;
import com.tudouji.project.flow.utils.FlowProcessUtil;
import com.tudouji.project.organization.domain.Department;
import com.tudouji.project.organization.domain.Organization;
import com.tudouji.project.organization.mapper.DepartmentMapper;
import com.tudouji.project.organization.mapper.OrganizationMapper;
import com.tudouji.project.permission.domain.Salespermission;
import com.tudouji.project.permission.service.impl.SalespermissionServiceImpl;
import com.tudouji.project.produce.domain.Pickinglist;
import com.tudouji.project.produce.domain.Scrapapply;
import com.tudouji.project.produce.domain.Scrapapplyitem;
import com.tudouji.project.produce.mapper.PickinglistMapper;
import com.tudouji.project.produce.mapper.ScrapapplyMapper;
import com.tudouji.project.produce.mapper.ScrapapplyitemMapper;
import com.tudouji.project.produce.service.IScrapapplyService;
import com.tudouji.project.product.domain.Salesspecification;
import com.tudouji.project.product.mapper.SalesspecificationMapper;
import com.tudouji.project.store.domain.Storehouseroom;
import com.tudouji.project.store.domain.Storeroom;
import com.tudouji.project.store.mapper.StorehouseroomMapper;
import com.tudouji.project.store.mapper.StoreroomMapper;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.service.impl.BusinesscodeServiceImpl;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 报废单Service业务层处理
 *
 * @author tudouji
 * @date 2022-06-01
 */
@Service
public class ScrapapplyServiceImpl implements IScrapapplyService
{
    @Autowired
    private ScrapapplyMapper scrapapplyMapper;
    @Autowired
    private StoreroomMapper storeroomMapper;
    @Autowired
    private StorehouseroomMapper storehouseroomMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private BusinesscodeServiceImpl businesscodeService;
    @Autowired
    private WhoutformServiceImpl outService;
    @Autowired
    private WhoutformitemServiceImpl outItemService;
    @Autowired
    private ScrapapplyitemMapper scrapapplyitemMapper;
    @Autowired
    private FlowProcessUtil processUtils;
    @Autowired
    private SalespermissionServiceImpl permissionService;
    @Autowired
    private PickinglistMapper pickinglistMapper;
    @Autowired
    private SalesspecificationMapper salesspecificationMapper;
    @Autowired
    private WhinfoServiceImpl whinfoService;

    /**
     * 查询报废单
     *
     * @param guid 报废单ID
     * @return 报废单
     */
    @Override
    public Scrapapply selectScrapapplyById(String guid)
    {
        return scrapapplyMapper.selectScrapapplyById(guid);
    }
    /**
     * 设置请求分页数据
     */
    protected void startPage()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (com.tudouji.common.utils.StringUtils.isNotNull(pageNum) && com.tudouji.common.utils.StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }
    /**
     * 查询报废单列表
     *
     * @param scrapapply 报废单
     * @return 报废单
     */
    @Override
    public List<Scrapapply> selectScrapapplyList(Scrapapply scrapapply)
    {
        return scrapapplyMapper.selectScrapapplyList(scrapapply);
    }

    /**
     * 新增报废单
     *
     * @param scrapapply 报废单
     * @return 结果
     */
    @Override
    public int insertScrapapply(Scrapapply scrapapply)
    {
        return scrapapplyMapper.insertScrapapply(scrapapply);
    }

    /**
     * 修改报废单
     *
     * @param scrapapply 报废单
     * @return 结果
     */
    @Override
    public int updateScrapapply(Scrapapply scrapapply)
    {
        return scrapapplyMapper.updateScrapapply(scrapapply);
    }

    /**
     * 批量删除报废单
     *
     * @param guids 需要删除的报废单ID
     * @return 结果
     */
    @Override
    public int deleteScrapapplyByIds(String[] guids)
    {
        return scrapapplyMapper.deleteScrapapplyByIds(guids);
    }

    /**
     * 删除报废单信息
     *
     * @param guid 报废单ID
     * @return 结果
     */
    @Override
    public int deleteScrapapplyById(String guid)
    {
        return scrapapplyMapper.deleteScrapapplyById(guid);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult save(Scrapapply scrapapply, String fileIds) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        scrapapply.setFlowid("32");
        scrapapply.setCode(businesscodeService.getCode("28"));
        scrapapply.setOperatorid(sysUser.getTuserId());
        scrapapply.setCreateBy(sysUser.getUserId());
        scrapapply.setStatus(-1);

        Department department = departmentMapper.selectDepartmentById(scrapapply.getDepartid());
        scrapapply.setDeptId(department.getId());
        scrapapply.setDeptName(department.getName());

        Organization organization = organizationMapper.selectOrganizationById(scrapapply.getOrgguid());
        scrapapply.setOrgname(organization.getName());
        scrapapply.setOrgId(organization.getId());

        Storeroom room = storeroomMapper.selectStoreroomByGuid(scrapapply.getSrguid());
        scrapapply.setSrguid(room.getGuid());
        scrapapply.setStrmId(room.getId());

        String guid = IdUtils.fastSimpleUUID();
        scrapapply.setGuid(guid);
        scrapapplyMapper.insertScrapapply(scrapapply);

        BigDecimal weight=new BigDecimal(0);
        BigDecimal amount=new BigDecimal(0);
        for(Scrapapplyitem item:scrapapply.getItems()){
            item.setScrapapplyid(guid);
            weight=weight.add(outService.calculateWeight(item.getSpecguid(), item.getWeight(), null, 3).get("toT"));
            amount=amount.add(item.getAmount()!=null?item.getAmount():BigDecimal.ZERO);
            item.setScrapapplyid(guid);
            item.setGuid(IdUtils.fastSimpleUUID());
            scrapapplyitemMapper.insertScrapapplyitem(item);
        }

        scrapapply.setPlatformId(scrapapply.getStrmId());
        FlowResult result = processUtils.defaultStart(processUtils.getStartNode(Long.valueOf(scrapapply.getFlowid()))
                , scrapapply, fileIds, sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Scrapapply mApply = new Scrapapply();
            mApply.setGuid(guid);
            mApply.setStatus(result.getNextStat());
            mApply.setWeight(weight);
            mApply.setAmount(amount);
            scrapapplyMapper.updateScrapapply(mApply);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult approval(Long id, String imgids, String opinion, Long taskid) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Scrapapply scrapapply = scrapapplyMapper.selectScrapapplyByNewId(id);

        scrapapply.setPlatformId(scrapapply.getStrmId());
        FlowResult result = processUtils.defaultApproval(taskid, imgids, opinion, scrapapply
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Scrapapply mApply = new Scrapapply();
            mApply.setStatus(result.getNextStat());
            mApply.setGuid(scrapapply.getGuid());
            this.updateScrapapply(mApply);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult refuse(Long id, String fileIds, String opinion, Long taskid, Long refuseNodeid, Long backUserid) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Scrapapply scrapapply = scrapapplyMapper.selectScrapapplyByNewId(id);

        scrapapply.setPlatformId(scrapapply.getStrmId());
        FlowResult result = processUtils.defaultRefuse(taskid, fileIds, opinion, scrapapply
                , sysUser, refuseNodeid, backUserid);

        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Scrapapply mApply = new Scrapapply();
            mApply.setStatus(result.getNextStat());
            mApply.setGuid(scrapapply.getGuid());
            this.updateScrapapply(mApply);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    public List<Scrapapply> selectScrapapplyList(Scrapapply scrapapply, String status, String functionType) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (scrapapply == null) {
            scrapapply = new Scrapapply();
        }

        if (org.apache.commons.lang.StringUtils.isNotBlank(status)) {
            if (status.equals("00")) {// 待处理
                scrapapply.setCreateBy(sysUser.getUserId());
                startPage();
                return scrapapplyMapper.selectScrapapplyPendingList(scrapapply);
            } else {
                String[] sts = status.split(",");
                Integer[] stss = (Integer[]) ConvertUtils.convert(sts, Integer.class);
                scrapapply.setStats(stss);
            }
        }
        //查询是否有全局权限
        List<Salespermission> permissions = permissionService.getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "4");
        if (permissions.size() > 0) {
            startPage();
            return scrapapplyMapper.selectScrapapplyList(scrapapply);
        } else {
            scrapapply.setCreateBy(sysUser.getUserId());
            // 是否有组织权限
            List<Salespermission> permissionsOrg = permissionService
                    .getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "7");
            //是否有部门权限
            permissions = permissionService.getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "2");

            startPage();
            if (permissions.size() > 0 || permissionsOrg.size() > 0) {
                String[] deptids = new String[permissions.size()];
                for (int i = 0; i < permissions.size(); i++) {
                    deptids[i] = permissions.get(i).getDepartid();
                }
                String[] roomids = new String[permissionsOrg.size()];
                for (int i = 0; i < permissionsOrg.size(); i++) {
                    roomids[i] = permissionsOrg.get(i).getSrguid();
                }
                scrapapply.setRoomids(roomids);
                scrapapply.setDepids(deptids);
                return scrapapplyMapper.selectScrapapplyByDep(scrapapply);
            } else {
                //查询个人的
                return scrapapplyMapper.selectScrapapplyByUser(scrapapply);
            }
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult scrapWhout(Whoutform whoutform, Long taskid, Long id, String opinion, String fileIds) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Scrapapply apply = scrapapplyMapper.selectScrapapplyByNewId(id);
        //获取领料单
        if(StringUtils.isNotBlank(apply.getPickinglistid())){
            Pickinglist pick = pickinglistMapper.selectPickinglistById(apply.getPickinglistid());
        }
        //组装出库单
        whoutform=new Whoutform();
        whoutform.setDepartmentid(apply.getDepartid());
        whoutform.setSrguid(apply.getSrguid());
        whoutform.setOuttype(5);
        whoutform.setOrderguid(apply.getGuid());
        whoutform.setOrgguid(apply.getOrgguid());
        whoutform.setOrgname(apply.getOrgname());
        whoutform.setOperatorid(sysUser.getTuserId());
        whoutform.setBusinesscode(apply.getCode());
        whoutform.setCreatetime(new Date());
        whoutform.setIsCopytoKD(1);
        /*String resultOut = */saveWhoutform(whoutform.getItems(), whoutform, apply);
//        if ("nowhinfo".equals(resultOut)){
//            return AjaxResult.error("库存不足！");
//        }

        apply.setPlatformId(apply.getStrmId());
        FlowResult result = processUtils.defaultApproval(taskid, fileIds, opinion, apply
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Scrapapply mApply = new Scrapapply();
            mApply.setStatus(result.getNextStat());
            mApply.setGuid(apply.getGuid());
            this.updateScrapapply(mApply);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    public Double getSumWeight(Scrapapply scrap) {
        return scrapapplyMapper.getSumWeight(scrap);
    }

    public String saveWhoutform(List<Whoutformitem> items, Whoutform outform, Scrapapply apply){
        outform.setBusinesscode(apply.getCode());
        outform.setWhoutcode(businesscodeService.getCode("7"));
        outform.setOuttime(new Date());
        outform.setCreatetime(new Date());
        String guid = IdUtils.fastSimpleUUID();
        outform.setGuid(guid);
        outService.insertWhoutform(outform);
        // 保存明细
        BigDecimal weight = new BigDecimal(0);
        BigDecimal countamount = new BigDecimal(0);
        for (Whoutformitem item : items) {
            item.setSrguid(apply.getSrguid());
            item.setWhoutid(guid);
            item.setOrgname(outform.getOrgname());
            item.setOrgguid(outform.getOrgguid());

            Storehouseroom house = storehouseroomMapper.selectStorehouseroomById(item.getShrguid());

            if (house.getShrtype()==1) {//原料
                Salesspecification spe=new Salesspecification();
                spe.setProductguid(item.getProductguid());
                spe.setBaseFlag(1);
                spe=salesspecificationMapper.selectSalesspecificationList(spe).get(0);
                item.setSpguid(spe.getGuid());
                item.setSpename(spe.getName());
            }

            item.setGuid(IdUtils.fastSimpleUUID());
            outItemService.insertWhoutformitem(item);
            weight = weight.add(item.getWeight());

            // 更新库存
            Whinfo info = new Whinfo();
//			if (house.getShrtype()==1) {// 原料
//				info = infoService.getWhinfo(outform.getOrgguid(), item.getProductguid(), item.getSrguid(),
//						item.getShrguid());
//			} else {// 产品
            info = whinfoService.getWhinfo(outform.getOrgguid(), item.getProductguid(), item.getSrguid(),
                    item.getShrguid(), item.getSpguid());
//			}
            if (info != null) {
                BigDecimal lef = info.getStoreqty().subtract(item.getWeight());
                if (lef.compareTo(BigDecimal.ZERO) > -1) {
                    info.setStoreqty(info.getStoreqty().subtract(item.getWeight()));
                    whinfoService.updateWhinfo(info);

                    // 更新申请单单价
                    Scrapapplyitem it = new Scrapapplyitem();
                    it.setGuid(item.getScrapitemid());
                    it.setAmount(info.getPrice() == null ? BigDecimal.ZERO : info.getPrice());
                    scrapapplyitemMapper.updateScrapapplyitem(it);
                    countamount = countamount.add(
                            (info.getPrice() == null ? BigDecimal.ZERO : info.getPrice()).multiply(item.getWeight()));
                } else {
//                    return "nowhinfo";
                    throw new CustomException("库存不足！");
                }
            } else {
//                return "nowhinfo";
                throw new CustomException("库存不足！");
            }
        }
        // 更新入库单总重量
        Whoutform out = new Whoutform();
        out.setGuid(guid);
        out.setWeight(weight);
        outService.updateWhoutform(out);

        // 更新申请单报废总额/状态
        apply.setAmount(countamount);
        // apply.setStatus(5);
        scrapapplyMapper.updateScrapapply(apply);
        return guid;
    }
}
